from django.views.generic import View
from ..forms import PubParamForm
from ..models import PubParamModel
from utils.messages import Json_Response, Form_Invalid
from utils.decorators import permission_verify
from utils.paginate import paginate
from utils.record import record
from copy import deepcopy


class PubParamView(View):
    @permission_verify(40008)
    def insert(self, request):
        form = PubParamForm.Insert(request.payload)
        if form.is_valid():
            data = form.cleaned_data
            if PubParamModel.objects.filter(name=data['name']):
                return Json_Response(code=201, err_msg='已经存在')
            obj = PubParamModel.objects.create(**data)
            record(request, 11, obj)
            return Json_Response(msg='新增成功')
        else:
            return Form_Invalid(form)

    @permission_verify(40008)
    def delete(self, request):
        form = PubParamForm.Delete(request.payload)
        if form.is_valid():
            data = form.cleaned_data
            id = data['id']
            for obj in PubParamModel.objects.filter(id=id):
                obj_copy = deepcopy(obj)
                obj.delete()
                record(request, 12, obj_copy)
            return Json_Response(msg='删除成功')
        else:
            return Form_Invalid(form)

    @permission_verify(40008)
    def update(self, request):
        form = PubParamForm.Update(request.payload)
        if form.is_valid():
            data = form.cleaned_data
            id = data.pop('id')
            qs = PubParamModel.objects.filter(id=id)
            qs.update(**data)
            for obj in qs:
                obj.save()
                record(request, 13, obj)
            return Json_Response(msg='修改成功')
        else:
            return Form_Invalid(form)

    @permission_verify(40007)
    def list(self, request):
        form = PubParamForm.List(request.payload)
        if form.is_valid():
            result = []
            data = form.cleaned_data
            page, page_size = data.pop('page'), data.pop('page_size')
            qs = PubParamModel.objects.filter()
            total = qs.count()
            for obj in paginate(qs, page, page_size).values_list(
                    'id', 'name', 'value', 'project__id', 'project__proj_name', named=True):
                result.append({
                    'id': obj.id,
                    'name': obj.name,
                    'value': obj.value,
                    'project': {
                        'id': obj.project__id,
                        'name': obj.project__proj_name,
                    }
                })
            return Json_Response(msg='查询成功', data={
                'page': page,
                'page_size': page_size,
                'total': total,
                'result': result
            })
        else:
            return Form_Invalid(form)
